/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr)
            return nullptr;
        if (head->next == nullptr)
            return head;
        ListNode* prev = head;
        ListNode* pprev = nullptr;
        ListNode* cur = head->next;
        ListNode* _next = cur->next;
        head = cur;
        while (1) {
            cur->next = prev;
            prev->next = _next;
            if(pprev) pprev->next = cur;
            if (!_next || !_next->next)
                break;
            else {
                pprev = prev;
                prev = _next;
                cur = _next->next;
                _next = cur->next;
            }
        }
        return head;
    }
};